package com.yanx.framework.filter;

import com.yanx.common.utils.Json_;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@Slf4j
@WebFilter(filterName = "XssFilter", urlPatterns = "/*")
public class XssFilter implements Filter {

    @Value("${my.filter.xss:false}")
    private boolean FILTER_XSS;

    @Value("${my.filter.xss.debug:false}")
    private boolean FILTER_XSS_DEBUG;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (FILTER_XSS) {
            if (FILTER_XSS_DEBUG) {
                log.debug("before xss filter paramter:{}", Json_.toJson(request.getParameterMap()));
            }
            XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
            if (FILTER_XSS_DEBUG) {
                log.debug("after xss filter paramter:{}", Json_.toJson(xssRequest.getParameterMap()));
            }
            chain.doFilter(xssRequest, response);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }

}
